//
//  Status.swift
//  weibo117
//
//  Created by 宋禹奇 on 15/7/2.
//  Copyright © 2015年 宋禹奇. All rights reserved.
//

import UIKit
import SDWebImage

//访问微博首页
private let WB_Home_Timeline_URL = "2/statuses/home_timeline.json"

class Status: NSObject {
   
    //微博创建时间
    var created_at: String?
    
    //微博ID
    var id: Int = 0
    
    //微博信息内容
    var text:String?
    
    //微博来源
    var source: String?
    
    //配图数组
    var pic_urls: [[String: String]]?{
        didSet {
            imageURLs = [NSURL]()
            largeImageURLs = [NSURL]()

            for dict in pic_urls!{
                var urlString = dict["thumbnail_pic"]!
                
                imageURLs?.append(NSURL(string: urlString)!)
                
                urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString:"large")
//                urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
//                    // 大图 URL
//                    largeImageURLs?.append(NSURL(string: urlString)!)"large")
                largeImageURLs?.append(NSURL(string: urlString)!)
                
            }
        }
    
    }
    
    //配图的URL 数组
    private var imageURLs: [NSURL]?
    
    //计算型属性,配图的URL数组
    //如果是转发微博,只需要缓存转发微博的imageURLs , 原创微博内容为空
    //如果是原创微博, imageURLs可能有内容
    var picURLs: [NSURL]?{
    
        return retweeted_status != nil ? retweeted_status?.imageURLs : imageURLs
    
    }
    
    //大图的URL 数组
    private var largeImageURLs: [NSURL]?
    var largePicURLs: [NSURL]? {
        return retweeted_status != nil ? retweeted_status?.largeImageURLs : largeImageURLs
    }
    
    
    //用户模型
    var user: User?
    //被转发的原微博信息字段，当该微博为转发微博时返回
    var retweeted_status: Status?

    
    //类属性数组
    static let properties = ["created_at","id","text","source","pic_urls","user","retweeted_status"]
    
    //字典转模型函数

    init(dict: [String: AnyObject]){
        super.init()
        
        for key in Status.properties{
        
            if dict[key] == nil || key == "user" || key == "retweeted_status"{
                continue
            }
            setValue(dict[key], forKey: key)
        }
        if let userDict = dict["user"] as? [String: AnyObject]{
        
            user = User(dict: userDict)
         
        }
        
        //判断字典中是否存在retweeted_status
        if let retweetedDict = dict["retweeted_status"] as? [String: AnyObject] {
        
            retweeted_status = Status(dict: retweetedDict)
        
        }
        
    }
    
    override var description: String{
        let dict = dictionaryWithValuesForKeys(Status.properties)
        return "\(dict)"
    }
    
    
    //加载数据
    //since_id    若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    //max_id      若指定此参数，则返回ID小于或等于max_id的微博，默认为0
    class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [Status]?, error: NSError?) -> ()) {
        assert(sharedUserAccount != nil,"必须登录之后才能访问网络")
        
        var params = ["access_token": sharedUserAccount!.access_token]
        
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            params["since_id"] = "0"
            params["max_id"] = "\(max_id - 1)"
        }
        
        //发起网络请求,异步加载数据
        NetworkTools.sharedNetworkTools().GET(WB_Home_Timeline_URL, parameters: params, success: { (_, JSON) -> Void in
            
            //从加载数据中取出微博数组
            if let array = JSON["statuses"] as? [[String: AnyObject]]{
                
                //获取微博的模型数组
                let list = statuses(array)
                
                print(list)
                //异步缓存微博中的所有图像
                cacheWebImages(list,finished: finished)
              
                return
            
            }
            //回调空数组,解析失败或其他原因
            finished(statuses: nil, error: nil)
            
            }) { (_, error) -> Void in
                //一定要保留,出错可以查找出错误
                print(error)
                //回调通知错误
                finished(statuses: nil, error: error)
        }
    }
    
    //缓存微博中所有的图片
    private class func cacheWebImages(list: [Status], finished: (statuses: [Status]?, error: NSError?) -> ()) {
        //定义调度组
        let group = dispatch_group_create()
        
        //遍历数组
        for s in list {
            //判断数组中是否有内容
            if s.picURLs == nil || s.picURLs!.isEmpty {
                continue
            }
            
            print(s.picURLs)
            //进一步遍历 imageurls 数组中 缓存的图片
            for url in s.picURLs! {
                //进入调度组
                dispatch_group_enter(group)
                
                //用SDWebImage 缓存图片  downloadImageWithURL 是 核心下载图片函数
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    //代码到此 说明图片已经缓存完毕了
                    
                    //离开调度组,图片缓存完毕
                    dispatch_group_leave(group)
                })
      
            }
        }
        
        //监听群组调度执行
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //完成回调
            finished(statuses: list, error: nil)
        }
    
    
    }
    //使用传入的数组，完成网络模型转 Status 数组
    private class func statuses(array: [[String: AnyObject]]) -> [Status]{
        //定义可变数组
        var arrayM = [Status]()
        //遍历array
        for dict in array{
        
            arrayM.append(Status(dict: dict))
        
        }
    
        return arrayM
    }
    
    
    
    
    
    
    
    
    
    
}
